<template>
<div class="adoptCouponList">
  <search-block type="flex">
    <template slot="button">
      <el-button type="primary" @click="search(true)">查询</el-button>
      <el-button type="primary" @click="generate">新建批次</el-button>
    </template>
    <el-form inline :model="model">
      <el-form-item label="券批次:">
        <el-input v-model="model.batchCode" clearable></el-input>
      </el-form-item>
      <el-form-item label="券种类:">
        <el-cascader
          v-model="varietyVal"
          :key="cateKey"
          clearable
          :options="cateOptions"
          :props="{
            label: 'cateName',
            value: 'cateCode'
          }"></el-cascader>
      </el-form-item>
    </el-form>
  </search-block>
  <y-table
    ref="table"
    border
    pagination
    :getDataWay="getDataWay"
    :columns="columns">
    <el-table-column slot="status" label="状态" align="center" header-align="center" width="100">
      <template v-slot="{row}">
        <span v-if="row.status === 0" class="y-warning">未发行</span>
        <span v-if="row.status === 1" class="y-success">已发行</span>
      </template>
    </el-table-column>
    <el-table-column slot="y-oper" label="操作" align="center" header-align="center" width="230">
      <template v-slot="{row}">
        <div class="table-buttons">
          <template v-if="row.status === 0">
            <el-popconfirm
              title="该批次券一旦发行无法更改或删除，请确认是否发行？"
              @confirm="applyCoupon(row)">
              <el-button slot="reference" type="primary" size="mini" >发行券</el-button>
            </el-popconfirm>
            <el-button type="primary" size="mini" @click="editCoupon(row)">编辑</el-button>
            <el-popconfirm
                title="是否确认删除该券？"
                @confirm="delCoupon(row)">
              <el-button slot="reference" type="danger" size="mini">删除</el-button>
            </el-popconfirm>
          </template>
          <template v-if="row.status === 1">
            <el-button size="mini" @click="viewCoupon(row)">查看券</el-button>
            <el-button size="mini" @click="exportCoupon(row)">导出</el-button>
          </template>
        </div>
      </template>
    </el-table-column>
  </y-table>
  <y-form
    v-model="forms.formModel"
    :visible.sync="forms.showForm"
    :title="forms.formTypeTitle[forms.formsType]"
    destroy-on-close
    force-inner-scroll
    width="50%"
    :form-attrs="forms.formAttrs"
    :columns="formColumns"
    @ensure="ensureModel">
    <el-cascader
      slot="variety"
      v-model="varietyModelVal"
      :options="cateOptions"
      :props="{
          label: 'cateName',
          value: 'cateCode'
        }"></el-cascader>
  </y-form>
  <el-dialog
    :title="`【${itemForms.row.batchName || '认领券'}】发行情况${Date.parse(itemForms.row.deadLine + ' 23:59:59') < Date.now() ? ('(' + '已过期' + ')') : ''}`"
    class="force-inner-scroll"
    :visible.sync="itemForms.show"
    @opened="openItem"
    destroy-on-close
    width="900px">
    <adopt-coupon-item-list
      ref="couponItem"
      ></adopt-coupon-item-list>
  </el-dialog>
</div>
</template>

<script>
import adoptCouponItemList from "@/views/sem/adoptCouponItemList";
export default {
  name: "adoptCouponList",
  components: { adoptCouponItemList },
  provide(){
    return{
      getBatchParam: (function(){
        return {
          batchId: this.itemForms.row.id
        };
      }).bind(this)
    }
  },
  computed:{
    getDataWay(){
      return {
        dataType: 'url',
        data: this.$api.sem.adoptCouponBatchList,
        param: this.model
      }
    },
    varietyVal:{
      get(){
        let ary = [];
        if(this.model.kind){
          ary.push(this.model.kind);
          if(this.model.variety){
            ary.push(this.model.variety);
          }
        }
        return ary;
      },
      set(val = []){
        val = val || [];
        [this.model.kind = '', this.model.variety = ''] = val;
        if(!val.length) this.cateKey ++;
      }
    },
    varietyModelVal:{
      get(){
        let ary = [];
        if(this.forms.formModel.kind){
          ary.push(this.forms.formModel.kind);
          if(this.forms.formModel.variety){
            ary.push(this.forms.formModel.variety);
          }
        }
        return ary;
      },
      set(val = []){
        val = val || [];
        [this.forms.formModel.kind = '', this.forms.formModel.variety = ''] = val;
      }
    },
    formColumns(){
      return [
        {
          label: "券编码前缀",
          prop: "cardPrefix",
          comp:{
            compType: 'YCodeSelect',
            attrs: {
              dict: 'SEM_COUPON_PREFIX'
            }
          }
        },
        {
          label: "券种类",
          prop: "variety",
          template: true
        },
        {
          label: "券名称",
          prop: "batchName",
          comp:{
            compType: 'input',
            attrs:{
              maxlength: 30,
              showWordLimit: true
            }
          }
        },
        /*{
          label: "图片",
          prop: "icon",
          comp:{
            compType: 'YUploadImg',
            attrs:{
              url: this.forms.formModel.icon ? [{
                url: this.forms.formModel.icon,
                id: this.forms.formModel.attachmentId
              }] : [],
              valueType: "ObjectArray",
              businessSysModuleCode: "ADOPT_COUPON",
              limit: 1,
              reUpload: true,
              cropperOptions:{
                fixed: false
              }
            },
            listeners:{
              update: this.updateModel
            }
          }
        },*/
        {
          label: "券说明",
          prop: "intro",
          comp:{
            compType: 'input',
            attrs:{
              type: 'textarea',
              maxlength: 200,
              showWordLimit: true,
              autosize: {
                minRows: 3
              }
            }
          }
        },
        {
          label: "发行数量(张)",
          prop: "count",
          comp:{
            compType: 'input-number',
            attrs:{
              stepStrictly: true
            }
          }
        },
        {
          label: "截止日期",
          prop: "deadLine",
          comp:{
            compType: 'datePicker',
            attrs: {
              type: "date",
              pickerOptions:{
                disabledDate(time) {
                  return time.getTime() < Date.now();
                },
                shortcuts: [{
                  text: '今天',
                  onClick(picker) {
                    picker.$emit('pick', new Date());
                  }
                }]
              },
              valueFormat: 'yyyy-MM-dd'
            }
          }
        }
      ]
    }
  },
  data(){
    return {
      cateOptions: [],
      cateKey: 0,
      model: {
        kind: '',
        variety: '',
        batchCode: '',
      },
      columns: [
        {
          label: "券批次",
          prop: "batchCode"
        },
        {
          label: "券名称",
          prop: "batchName"
        },
        {
          label: "券种类",
          prop: "variety",
          formatter: (function(row){
            return this.getVarietyName(row.kind, row.variety);
          }).bind(this)
        },
        /*{
          label: "可用数量(张)",
          prop: "unUsedCount",
          formatter: ({unUsedCount}) => unUsedCount || 0,
          width: 102
        },*/
        {
          label: "发行总量(张)",
          prop: "count",
          width: 102
        },
        {
          label: "截止时间",
          prop: "deadLine",
          minWidth: 130,
          formatter(row){
            return (row.deadLine || '').replace('T', ' ');
          }
        },
        {
          prop: "status",
          template: true
        }
      ],
      forms:{
        formsType: '',
        formTypeTitle: {
          'ADD': '新建批次',
          'EDIT': '编辑批次'
        },
        formModel:{
          cardPrefix: '',
          kind: '',
          variety: '',
          count: '',
          deadLine: '',
          batchName: '',
          attachmentId: '',
          icon: '',
          intro: ''
        },
        currentForm: null,
        showForm: false,
        formAttrs: {
          labelWidth: '120px',
          rules: {
            cardPrefix: [{required: true, message: "请选择券编码前缀", trigger: "change"}],
            variety: [{required: true, message: "请选择券种类", trigger: "change"}],
            count: [
              {required: true, message: "请输入发行数量", trigger: "blur"},
              { type: 'number', min: 1, message: '请输入发行数量', trigger: 'blur' },
              { type: 'number', max: 99999, message: '不得超过最大发行数量：99999', trigger: 'blur' }
            ],
            batchName: [{required: true, message: "请输入券名称", trigger: "blur"}],
            deadLine: [
              {required: true, message: "请选择券截止时间", trigger: "change"}
            ]
          }
        }
      },
      itemForms:{
        row: {},
        show: false
      }
    }
  },
  created(){ this.initInfo() },
  methods:{
    initInfo(){
      this.$yAxios({
        url: this.$api.adopt.queryAdoptCategory
      }, info => {
        this.cateOptions = info.filter(item => !!item.children);
      })
    },
    search(jumpToFirst){
      this.$refs['table'] && this.$refs['table'].loadData(this.model, jumpToFirst);
    },
    resetForm(){
      Object.keys(this.forms.formModel).map(key => {
        this.forms.formModel[key] = this.forms.currentForm ? this.forms.currentForm[key] : '';
      })
    },
    generate(){
      this.forms.formsType = 'ADD';
      this.forms.currentForm = null;
      this.resetForm();
      this.forms.showForm = true;
    },
    editCoupon(row){
      this.forms.formsType = 'EDIT';
      this.forms.currentForm = row;
      this.resetForm();
      this.forms.showForm = true;
    },
    viewCoupon(row){
      this.$set(this.itemForms, 'row', row);
      this.itemForms.show = true;
    },
    exportCoupon(row){
      this.$yAxios({
        url: this.$api.sem.exportAdoptCouponBatch,
        data:{
          batchId: row.id
        },
        loading: true
      }, info => {
        if(info?.length){
          let data = [
            ['券编号', '券密码']
          ];
          data.push(...info.map(item => [item.cardCode, item.cardSecret]));
          this.$$exportExcel({
            data, fileName: row.batchName + '.xlsx'
          })
        }else{
          this.$message({
            type: 'warning',
            message: '该批次不存在已发行的券'
          });
        }
      })
    },
    applyCoupon(row){
      this.$yAxios({
        url: this.$api.sem.generateAdoptCouponBatch,
        data:{
          id: row.id
        },
        loading: true
      }, info => {
        this.$alert(`成功发行${row.count}张【${this.getVarietyName(row.kind, row.variety)}】认领券`);
        this.search();
      })
    },
    openItem(){
      this.$refs['couponItem'].search(true);
    },
    delCoupon(row){
      this.$yAxios({
        url: this.$api.sem.removeAdoptCouponBatch,
        data:{
          id: row.id
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: '删除成功'
        });
        this.search();
      })
    },
    ensureModel(form){
      let newForm, url = this.$api.sem.saveAdoptCoupon;
      if(this.forms.formsType === 'EDIT'){
        newForm = Object.assign({}, this.forms.currentForm, form);
      }else{
        newForm = form
      }
      this.$yAxios({
        url,
        data: newForm,
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: '保存成功'
        });
        this.search(this.forms.formsType === 'ADD');
      })
    },
    getVarietyName(kind, variety){
      if(!kind || !this.cateOptions.length) return '';
      let str = ''
      let kindObj = this.cateOptions.find(cd => cd.cateCode === kind);
      if(!kindObj) return '';
      str += kindObj.cateName;
      if(variety && kindObj.children && kindObj.children.length){
        let varietyObj = kindObj.children.find(vd => vd.cateCode === variety);
        if(varietyObj){
          str += '/' + varietyObj.cateName;
        }
      }
      return str;
    },
    updateModel({type, file}){
      switch(type) {
        case 'delete': {
          this.forms.formModel.attachmentId = '';
          this.forms.formModel.icon = '';
          break;
        }
        case 'edit': case 'add':{
          this.forms.formModel.attachmentId = file.id;
          this.forms.formModel.icon = file.name;
          break;
        }
      }
    }
  }
}
</script>

<style scoped lang="less">
.adoptCouponList{

}
</style>